package com.xqboss.apps.service.sys;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xqboss.apps.domain.sys.SysAppVersion;
import com.xqboss.apps.enums.sys.SaleableEnum;
import com.xqboss.apps.mapper.sys.SysAppVersionMapper;
import com.xqboss.common.core.domain.R;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * app版本管理接口
 *
 * @author wangcong
 * @date 2023-09-04
 */
@Service
public class SysAppVersionService extends ServiceImpl<SysAppVersionMapper, SysAppVersion> {

    public SysAppVersion verifyApp(String versionCode, String appCode) {
        LambdaQueryWrapper<SysAppVersion> wq = new LambdaQueryWrapper<>();
        wq.eq(SysAppVersion::getAppCode, appCode);
        wq.eq(SysAppVersion::getSaleable, SaleableEnum.SEQUENCE.getValue());
        wq.orderByDesc(SysAppVersion::getId);
        wq.last("limit 1");
        SysAppVersion appVersion = baseMapper.selectOne(wq);

//        if (appVersion != null) {
//            String code = appVersion.getVersionCode();
//            if (StrUtil.equals(appCode, "02")) {
//                code = appVersion.getVersionName();
//            }
//            int i = compareVersion(code, versionCode);
//            if (i == 1) {
//                return R.ok(appVersion);
//            }
//        }
        return appVersion;
    }

    /**
     * 版本号比较
     *
     * @param v1
     * @param v2
     * @return 0代表相等，1代表左边大，-1代表右边大
     * Utils.compareVersion("1.0.358_20180820090554","1.0.358_20180820090553")=1
     */
    public int compareVersion(String v1, String v2) {
        if (v1.equals(v2)) {
            return 0;
        }
        String[] version1Array = v1.split("[._]");
        String[] version2Array = v2.split("[._]");
        int index = 0;
        int minLen = Math.min(version1Array.length, version2Array.length);
        long diff = 0;

        while (index < minLen
                && (diff = Long.parseLong(version1Array[index])
                - Long.parseLong(version2Array[index])) == 0) {
            index++;
        }
        if (diff == 0) {
            for (int i = index; i < version1Array.length; i++) {
                if (Long.parseLong(version1Array[i]) > 0) {
                    return 1;
                }
            }
            for (int i = index; i < version2Array.length; i++) {
                if (Long.parseLong(version2Array[i]) > 0) {
                    return -1;
                }
            }
            return 0;
        } else {
            return diff > 0 ? 1 : -1;
        }
    }
}
